package com.future.lottie;


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @author xuchuanting
 * Create on 2020/7/28 14:39
 */
public class Main {

    public static void main(String[] args) {
        //API产品路径
        String requestUrl = "https://icalendar.market.alicloudapi.com/ai_metaphysics/calendar/elite?";
        //阿里云APPCODE
        String appcode = "阿里云APPCODE";
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();

        querys.put("STRING", "20180808080808");

        try {
            String response = get(requestUrl, headers, querys);
            System.out.println("response = " + response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String get(String url, Map<String, String> headers, Map<String, String> querys) throws IOException {
        //添加参数
        for (String key : querys.keySet()) {
            url += (key + "=" + URLEncoder.encode(querys.get(key), "utf-8") + '&');
        }
        url = url.substring(0, url.length() - 1);

        URL url1 = new URL(url);
        URLConnection urlConnection = url1.openConnection();
        urlConnection.setDoInput(true);
        // 必须设置下面这个Header
//        for (String key : headers.keySet()) {
//            urlConnection.
//        }

        urlConnection.connect();

        InputStream inputStream = urlConnection.getInputStream();
        byte[] bytes = new byte[1024];
        int len;
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        while ((len = inputStream.read(bytes)) != -1) {
            byteArrayOutputStream.write(bytes, 0, len);
        }
        byteArrayOutputStream.flush();
        inputStream.close();
        return byteArrayOutputStream.toString();
    }
}
